<?php
$username = trim($_POST['username']);
$password = trim($_POST['pw']);
$cpw = trim($_POST['cpw']);
$email = trim($_POST['email']);
$page = $_POST['page'];
if(!strlen($username)){
    //说明没填写用户名
    echo "<script>alert('用户名必须填写');history.back();</script>";
    exit;
}else{
    if(!preg_match('/^[a-zA-Z0-9]{3,10}$/',$username)){
        echo "<script>alert('用户名必填，只能有大小写字母和数字组成，3到十个字符！');history.back();</script>";
        exit;
    }
}
if(!empty($password)){
    if($password <> $cpw){
        echo "<script>alert('密码确认密码必须相同');history.back();</script>";
        exit;
    }else {
        if (!preg_match('/^[a-zA-Z0-9_*]{6,10}$/', $password)) {
            echo "<script>alert('密码必填，且只能大小写字符和数字，以及*号和_构成，长度6-10个字符');history.back();</script>";
            exit;
        }
    }
}
if (!empty($email)) {
    if (!preg_match('/^\w{3,12}@\w{1,5}\.[a-z]{2,3}$/', $email)) {
        echo "<script>alert('确认密码不相符！');history.back();</script>";
        exit;
    }
}
include_once 'conn.php';
if($password){//说明有更新密码，要变更密码
    $sql = "update userinfo set pw = '".md5($password)."',email = '$email'  where username = '$username'";
    if($page){
        //说明是管理员修改资料
        $url = 'admin.php?navID=4&page='.$page;
    }
    else{
        $url = 'logout.php';
    }
}else{
    $sql = "update userinfo set email = '$email' where username = '$username'";
    if($page){
        //说明是管理员修改资料
        $url = 'admin.php?navID=4&page='.$page;
    }
    else{
        $url = 'index.php';
    }
}
$result = mysqli_query($conn,$sql);
if($result){
    echo "<script>alert('更新个人资料成功！');location.href='$url';</script>";
}else{
    echo "<script>alert('更新个人资料失败！');history.back();</script>";
}